$(function () {
    var uiContent = $('#uiContent');

    $.wxJsApiConfig(function () {
        main();
    });

    function main() {
        var newsId = $.getUrlParam('newsId');
        if (!newsId) {
            $.gotoErrorPage(uiContent);
            return;
        }

        $.restClient('/mobile/prize/check/' + newsId, null, function (data) {
            if (data && data.status == 0) {
                if (data.data && !data.data.resultMessage) {
                    showForm(newsId);
                } else if (data.data && data.data.resultMessage && data.data.originalNewsUrl) {
                    $.alert(data.data.resultMessage, function () {
                        window.location.href = data.data.originalNewsUrl;
                    });
                } else {
                    $.gotoErrorPage(uiContent);
                }
            }
        });
    }

    function showForm(newsId) {
        uiContent.show();
        // 验证码
        var imgCaptcha = $('#imgCaptcha');
        imgCaptcha.attr('src', '/lego/captcha.jpg?time=' + (+new Date()));
        imgCaptcha.bind('click', function () {
            imgCaptcha.attr('src', '/lego/captcha.jpg?time=' + (+new Date()));
        });
        // 提交按钮
        var btnSubmit = $('#btnSubmit');
        btnSubmit.bind('click', function () {
            var telephone = $('#telephone').val();
            var againTelephone = $('#againTelephone').val();
            if (!(telephone && againTelephone && telephone == againTelephone)) {
                $.alert('请您务必输入手机号码，并保证两次输入的手机号码一模一样');
                return;
            }
            var captcha = $('#captcha').val();
            if (!captcha) {
                $.alert('请您务必填写验证码');
                return;
            }

            var json = {telephone: telephone, pushNews: {id: newsId}, captcha: captcha};
            $.restClient('/mobile/prize/add', $.toJSON(json), function (data) {
                if (data && data.status == 0) {
                    if (data.data && data.data.id) {
                        window.location.href = '/mobile/showPrizeCode.html?code=' + data.data.telephone + ':' + data.data.prizeCode;
                    } else {
                        $.alert(data.message, function () {
                            imgCaptcha.attr('src', '/lego/captcha.jpg?time=' + (+new Date()));
                            $('#captcha').val('');
                        });
                    }
                }
            });
        });
    }
});